package com.example.jdai.jdai.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.moblie.zmxy.antgroup.creditsdk.app.CreditApp;
import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.R;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.BackRest;
import com.example.jdai.jdai.rest.GetData;
import com.example.jdai.jdai.rest.RestApi;
import com.example.jdai.jdai.rest.SendCode;
import com.example.jdai.jdai.threeparty.FileUploadThread;
import com.example.jdai.jdai.threeparty.UpdataService;
import com.example.jdai.jdai.util.DataAll;
import com.example.jdai.jdai.util.Tools;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.R.attr.targetSdkVersion;

public class MainActivity extends Activity implements BackRest.DoLong,ActivityCompat.OnRequestPermissionsResultCallback {
    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    @BindView(R.id.tb)
    TopBar tb;
    @BindView(R.id.bb)
    BottomBar bb;
    @BindView(R.id.fr_content)
    FrameLayout frContent;
    @BindView(R.id.activity_main)
    RelativeLayout activityMain;
    Fragment[] fragments=new Fragment[2];
    int currentFr;
    @BindString(R.string.get_check)
    String myCheck;
    @BindString(R.string.get_people)
    String myPeople;
    public ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean isFail=getIntent().getBooleanExtra("isfail",false);
        if(!isFail) {
            if ((!"0".equals(MyApplication.dataAll.data.get(DataAll.IS_COMMIT)) &&
                    (!"".equals(MyApplication.dataAll.data.get(DataAll.IS_COMMIT)))
            )) {
                startActivity(new Intent(this, ScActivity.class));
                finish();
                return;
            }
        }
        if(Config.ISDEBUG)
            Log.v("main","main");
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        MyApplication.main=this;
        pd=new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        init();
        tb.setTopBarLisener(new TopBar.TopBarLisener() {
            @Override
            public void back() {
            }
            @Override
            public void more() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                //    设置Title的图标
                builder.setIcon(R.drawable.logo1);
                builder.setTitle("温馨提示");
                builder.setMessage("提交后将无法更改数据！");
                //    设置一个PositiveButton
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(DataAll.checkCanUp()){
                          commit();

                        }
                        else {
                            Toast.makeText(MainActivity.this,"必填项未填写完成",Toast.LENGTH_SHORT).show();
                        }

                    }
                }).show();
//               MyDialog myDialog= new MyDialog();
//                myDialog.setOkClick(new MyDialog.OkClick() {
//                    @Override
//                    public void clickOk() {
//
//
//                    }
//                });
//                myDialog.show(getFragmentManager(),"aa");
            }
        });
        bb.setBottomBarClick(new BottomBar.BottomBarClick() {
            @Override
            public void click(int id) {
                switch (id){
                    case R.id.bt_check:
                        setFragments(0);
                        //Log.v("dddd",id+"");
                        break;
                    case R.id.bt_my:
                        setFragments(1);
                        break;
                }

            }
        });
        setDefaultFragment();
        Tools.Update(this);

    }
    public void commit(){
        pd.setMessage("正在上传...");
        pd.show();
        MyApplication.backRest.CommitOk(MainActivity.this);

    }
    //设置默认fr
    private void setDefaultFragment()
    {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        fragments[0] = new CheckFragment();
        fragments[1]=new MyFragment();
        for(int i=0;i<fragments.length;i++){
            transaction.add(R.id.fr_content,fragments[i]).hide(fragments[i]);
        }
        transaction.show(fragments[0]);
        transaction.commit();
        currentFr=0;
    }
    //设置fr
    void setFragments(int index){
        if(currentFr!=index) {
            FragmentManager fm = getFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.hide(fragments[currentFr]);
            currentFr = index;
            transaction.show(fragments[currentFr]);
            transaction.commit();
            tb.disToggleRightVisable();
        }
        setTbTitle(index);
    }
    void setTbTitle(int index){
if (index==1)
    tb.setTitle(myPeople);
        else
    tb.setTitle(myCheck);
    }
    void init()
    {
        PermissionGet();
        MyApplication.location.start();


       // Update();

    }
    //获得权限
    void PermissionGet()
    {
        //int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
        };
        boolean permission3=Tools.selfPermissionGranted(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
        boolean permission = Tools.selfPermissionGranted(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean permission2 = Tools.selfPermissionGranted(MainActivity.this, Manifest.permission.READ_CONTACTS);
        boolean permission4 = Tools.selfPermissionGranted(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (permission&&permission2&&permission3&&permission4) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(!Tools.GetContacts()){
                        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        //    设置Title的图标
                        builder.setIcon(R.drawable.logo1);
                        builder.setTitle("缺少权限");
                        builder.setCancelable(false);
                        builder.setMessage("软件部分功能依赖通讯录，无法开启，请前往应用权限设置打开权限！");
                        //    设置一个PositiveButton
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                android.os.Process.killProcess(android.os.Process.myPid());

                            }
                        });
                        Tools.postToMain(new Runnable() {
                            @Override
                            public void run() {
                                builder.show();
                            }
                        });
                    }
                }
            }).start();
        }
        else {

            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS
            );
            if(Config.ISDEBUG){
                Log.v("pr",permission+";"+permission2+";"+permission3);
            }

        }
       // Tools.GetContacts();

        //Log.v("ddd","sssss");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(Config.ISDEBUG)
            Log.v("main_de","save");
        MyApplication.dataAll.saveAll();
        MyApplication.location.stop();
        //CreditApp.destroy();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Config.ISDEBUG)
        Log.d("sss", "DemoActivity.onActivityResult");
        //onActivityResult callback
       // CreditApp.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.backRest.getInfo_two(MainActivity.this);
        if(Config.ISDEBUG)
            Log.v("main_re","start");
        ((InitData)fragments[currentFr]).initData();

    }

    @Override
    public void doDone(int mark, Map str) {
        switch (mark){
            case 0:
                pd.dismiss();
                startActivity(new Intent(MainActivity.this,ScActivity.class));
                finish();
                break;
            case 1:
                if(Config.ISDEBUG)
                    Log.v("main_dodone","1");
                ((InitData)fragments[currentFr]).initData();
            case 404:
                pd.dismiss();
                Toast.makeText(this, "提交失败", Toast.LENGTH_SHORT).show();
                break;
            case 2000:
                ((InitData)fragments[currentFr]).initData();
                break;


        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if(Config.ISDEBUG)
            Log.v("ddd","pr");
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
            {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                //perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for ACCESS_FINE_LOCATION
                if ((perms.get(Manifest.permission.READ_EXTERNAL_STORAGE)) == PackageManager.PERMISSION_GRANTED
                        && ((int)perms.get(Manifest.permission.READ_CONTACTS)) == PackageManager.PERMISSION_GRANTED
                        && ((int)perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE)) == PackageManager.PERMISSION_GRANTED) {
                    return;
                    // All Permissions Granted
                } else {
                    // Permission Denied

                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    //    设置Title的图标
                    builder.setIcon(R.drawable.logo1);
                    builder.setTitle("缺少权限");
                    builder.setCancelable(false);
                    builder.setMessage("软件缺少相应权限，请到权限管理打开！");
                    //    设置一个PositiveButton
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            android.os.Process.killProcess(android.os.Process.myPid());

                        }
                    });
                    builder.show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
}



}
